#coding:utf-8
__author__ = 'nhsheng'

import requests,json,re
from common.Log import logger


'''判断是否是json格式数据'''
def check_json_format(msg):
    if isinstance(msg,str):
        try:
            json.loads(msg,encoding='utf-8')
        except ValueError:
            return False
        return  True
    else:
        return False


class requestUtils:

    def __init__(self):
        pass


    '''get,post通用方法'''
    def request_get_post(self,method,url,**kwargs):
        responses = requests.request(method,url,**kwargs)
        if responses.status_code == 200:
            respones_text = responses.text
            #logger().info(respones_text)
            if check_json_format(respones_text):
                return responses.json()
            else:
                return respones_text
        else:
            logger().error(url +' 接口调用报错:%s' %(str(responses.content,encoding='utf-8')))
            return {'code':responses.status_code}

    '''get请求'''
    def get(self,url,params=None,headers=None,file=None):
        try:
            if(url != ''):
                return  self.request_get_post('get',url,params=params,headers=headers,files=file)
        except Exception as e:
            pass
        #logger().error('get reqeust error')


   # '''post请求'''
    def post(self,url,data=None,headers=None,file=None,params=None):
        try:
            if(url != ''):
                if isinstance(params,dict):
                    for key,value in params.items():
                        url = url+key+'='+value+'&'
                    url = url[:-1]
                return self.request_get_post('post',url,data=data,headers=headers,files=file)
            else:
                logger().error('post url format error')
        except Exception:
            logger().error('post request error')

    def getUrl(self,url):
        if(url=='' or url==None or re.match(r'(.*)(\.com)',url)):
            logger().error('url format error')
        else:
            return url




if __name__ == '__main__':
    res = requestUtils()
    res.post('http://event.api.ulucu.com/event/add',params={'av':'1','token':'111'})